package com.lmmob.autotest.uitest.formmodel;

import cucumber.table.DataTable;
import org.apache.commons.lang.StringUtils;

import com.lmmob.autotest.uitest.controls.CheckBoxGroup;
import com.lmmob.autotest.uitest.controls.Combobox;
import com.lmmob.autotest.uitest.controls.Control;
import com.lmmob.autotest.uitest.controls.RadioButtonGroup;
import com.lmmob.autotest.uitest.controls.SuggestBox;
import com.lmmob.autotest.uitest.controls.TextArea;
import com.lmmob.autotest.uitest.controls.TextBox;
import com.lmmob.autotest.uitest.controls.TextBoxEx;
import com.lmmob.autotest.uitest.controls.ValueSettable;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FormObject {

    public FormObject(DataTable table) {
        init(table);
    }

    private void init(DataTable table) {
        List<List<String>> values = table.raw();
        Map<String, List<String>> map = parse(values);
        Class<? extends FormObject> clazz = this.getClass();
        Map<String, Field> fieldMap = new HashMap<String, Field>();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(FormField.class)) {
                FormField formField = field.getAnnotation(FormField.class);
                String text = formField.text();
                fieldMap.put(text, field);
            }
        }

        for (String key : map.keySet()) {
            setValue(map, fieldMap, key);
        }
    }

    private Map<String, List<String>> parse(List<List<String>> values) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (int i = 0; i < values.size(); ++i) {
            List<String> pair = values.get(i);
            map.put(pair.get(0), pair);
        }
        return map;
    }

    private void setValue(Map<String, List<String>> map, Map<String, Field> fieldMap, String key) {
        try {
            if (fieldMap.containsKey(key)) {
                Field field = fieldMap.get(key);
                field.setAccessible(true);
                List<String> value = map.get(key);
                if (value.size() == 3) {
                    FormElement formElement = new FormElement(value.get(1), value.get(2));
                    field.set(this, formElement);
                } else {
                    FormElement formElement = new FormElement(value.get(1), StringUtils.EMPTY);
                    field.set(this, formElement);
                }
            }
        } catch (IllegalAccessException e) {

        }
    }
    
    public FormElement getValue(Field field) {
        try {
            field.setAccessible(true);
            return (FormElement) field.get(this);
        } catch (IllegalAccessException e) {
            return null;
        }
    }
    
    
}
